package com.apes.exception;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.EsbRouter;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MessageChannel;
import com.apes.framework.plugin.outbox.OutboxSubscriber;
import com.apes.framework.plugin.outbox.OutboxSubscriberManager;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.exception
 * @ClassName: MessageService
 * @Author: pyb
 * @CreateTime: 2020-05-19 16:51
 * @Description: 异常消息服务
 * @Version: 1.0
 */
@Service("messageService")
public class MessageService extends DomainService {

    MessageSubscriberRepository messageSubscriberRepository;

    @Autowired
    private void setMessageSubscriberRepository(MessageSubscriberRepository messageSubscriberRepository) {
        this.messageSubscriberRepository = messageSubscriberRepository;
    }

    MessageTopicRepository messageTopicRepository;

    @Autowired
    private void setMessageTopicRepository(MessageTopicRepository messageTopicRepository) {
        this.messageTopicRepository = messageTopicRepository;
    }

    /**
     * 订阅查询方法前端格式化
     */
    public Object findAllSubscriberForUI(SimpleRequest request){
        Page<MessageSubscriber> messageSubscribers = request.getO(Page.class);
        messageSubscribers.getContent().stream().forEach(
                messageSubscriber -> {
                    if (!messageSubscriber.getMessageTopics().isEmpty()){
                        messageSubscriber.setOutBoxTopics(messageSubscriber.getMessageTopics().stream().filter(topic -> topic.getTopicType().equals("OutBox")).collect(Collectors.toList()));
                        messageSubscriber.setMQTopics(messageSubscriber.getMessageTopics().stream().filter(topic -> topic.getTopicType().equals("MQ")).collect(Collectors.toList()));
                        messageSubscriber.setESBTopics(messageSubscriber.getMessageTopics().stream().filter(topic -> topic.getTopicType().equals("ESB")).collect(Collectors.toList()));
                    }
                }
        );
        return messageSubscribers;
    }

    /**
     * 订阅者保存方法
     *
     * @param request
     * @return
     */
    public MessageSubscriber messageSubscriberSave(SimpleRequest request) {
        MessageSubscriber messageSubscriber = request.getO(MessageSubscriber.class);
        List<MessageTopic> messageTopics = new ArrayList<>();
        List<MessageTopic> outBoxTopics = request.getA("outBoxTopics", MessageTopic.class);
        List<MessageTopic> mqTopics= request.getA("MQTopics", MessageTopic.class);
        List<MessageTopic> esbTopics = request.getA("ESBTopics", MessageTopic.class);
        if (!outBoxTopics.isEmpty()){
            outBoxTopics.stream().forEach(topic -> {
                try {
                    topic.setTopic((String) JSONObject.parseObject(topic.getTopic()).get("id"));
                }catch (Exception e){}
                topic.setMessageSubscriber(messageSubscriber);
            });
            messageTopics.addAll(outBoxTopics);
        }
        if (!mqTopics.isEmpty()){
            mqTopics.stream().forEach(topic -> {
                topic.setMessageSubscriber(messageSubscriber);
            });
            messageTopics.addAll(mqTopics);
        }
        if (!esbTopics.isEmpty()) {
            esbTopics.stream().forEach(topic -> {
                try {
                    topic.setTopic((String) JSONObject.parseObject(topic.getTopic()).get("id"));
                }catch (Exception e){}
                topic.setMessageSubscriber(messageSubscriber);
            });
            messageTopics.addAll(esbTopics);
        }
        messageSubscriber.getMessageTopics().clear();
        messageSubscriber.setMessageTopics(messageTopics);
        return messageSubscriberRepository.saveAndFlush(messageSubscriber);
    }

    /**
     * 订阅者删除方法
     *
     * @param request
     * @return
     */
    public String messageSubscriberDelete(SimpleRequest request) {
        MessageSubscriber subscriber = request.getO(MessageSubscriber.class);
        messageSubscriberRepository.delete(subscriber.getId());
        return "删除成功";
    }

    /**
     * 订阅主题保存方法
     *
     * @param simpleRequest
     * @return
     */
    public MessageTopic messageTopicSave(SimpleRequest simpleRequest) {
        MessageTopic messageTopic = simpleRequest.getO(MessageTopic.class);
        if (null != messageTopic.getTopic() && messageTopic.getTopic().contains("{")) {
            messageTopic.setTopic((String) JSONObject.parseObject(messageTopic.getTopic()).get("id"));
        }
//        convertMessageSubscribers(messageTopic);
        MessageTopic result = messageTopicRepository.saveAndFlush(messageTopic);
//        result.convertMessageSubscribers();
        return result;
    }

    /**
     * 订阅主题删除方法
     *
     * @param request
     * @return
     */
    public String messageTopicDelete(SimpleRequest request) {
        MessageTopic subscriber = request.getO(MessageTopic.class);
        messageTopicRepository.delete(subscriber.getId());
        return "删除成功";
    }

    /**
     * 订阅主题内主题查询
     *
     * @param request
     * @return
     */
    public Page findByType(SimpleRequest request) {
        Map<String, String> map = new HashMap();
        request.getJO().getJSONObject("group").getJSONArray("filters").forEach(filter -> {
            JSONObject jo = (JSONObject) filter;
            map.put(jo.getString("field"), jo.getString("value"));
        });
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"));
        List result = new ArrayList<>();
        switch (map.get("topicType")) {
            case "OutBox":
                List<OutboxSubscriber> outboxSubscribers = SpringManager.getBean(OutboxSubscriberManager.class).getOutboxSubscribers();
                result = outboxSubscribers.stream().filter(m ->
                        m.getId().contains(request.get("key")) || (m.getName() != null && (m.getName().contains(request.get("key")))
                        )).collect(Collectors.toList());
                break;
            case "MQ":
                Set<String> keySet = SpringManager.getBean(MessageChannel.class).getConsumers().keySet();
                result=keySet.stream().filter(key -> {
                    return key.contains(request.get("key"));
                }).collect(Collectors.toList());

                break;
            default:
                return SpringManager.getBean(EsbRouter.class).getAllProcessor(request);
        }
        PageImpl page = new PageImpl<>(result, pageable, result.size());
        return page;
    }

    /**
     * 转换异常信息主题订阅者
     *
     * @param messageTopic
     */
//    private void convertMessageSubscribers(MessageTopic messageTopic) {
//        List<MessageSubscriber> messageSubscribers = messageTopic.getMessageSubscribers();
//        Set<MessageBinding> messageBindings = new HashSet<>();
//        Map<String, MessageBinding> bindingMap = messageBindings.stream().collect(Collectors.toMap(x -> x.getMessageSubscriber().getId(), x -> x));
//        //绑定主题订阅
//        messageSubscribers.forEach(subscriber -> {
//            MessageBinding messageBinding = new MessageBinding();
//            messageBinding.setMessageSubscriber(subscriber);
//            messageBinding.setMessageTopic(messageTopic);
//            if (!bindingMap.isEmpty() && bindingMap.containsKey(subscriber.getId())) {
//                messageBindings.add(bindingMap.get(subscriber.getId()));
//            } else {
//                messageBindings.add(messageBinding);
//            }
//        });
//        messageTopic.getMessageBindings().clear();
//        messageTopic.setMessageBindings(messageBindings);
//    }

    /**
     * 异常消息订阅界面转换
     *
     * @param simpleRequest
     * @return
     */
//    public Page<MessageTopic> findAllConvert(SimpleRequest simpleRequest) {
//        Page<MessageTopic> messageTopicPage = simpleRequest.getO(Page.class);
//        /*
//         * 转化格式
//         * */
//        messageTopicPage.getContent().stream().forEach(
//                (MessageTopic messageTopic) -> {
//                    // 转换
//                    messageTopic.convertMessageSubscribers();
//                }
//        );
//        return messageTopicPage;
//    }

}
